package com.wngbms.gatewaydemo.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

public class RemoveRequestParamFilter implements HttpRequestFilter {

    private String key;
    private HttpRequestFilter nextFilter;

    public RemoveRequestParamFilter() {
    }

    public RemoveRequestParamFilter(String key) {
        this.key = key;
    }

    public RemoveRequestParamFilter(HttpRequestFilter nextFilter) {
        this.nextFilter = nextFilter;
    }

    @Override
    public void filter(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) {
        String uri = fullHttpRequest.uri();
        fullHttpRequest.setUri(handleUri(uri));

        if (nextFilter != null) {
            nextFilter.filter(fullHttpRequest, ctx);
        }
    }

    public String handleUri(String uri) {
        int i1 = uri.indexOf("&" + key + "=");
        int i = i1 == -1 ? uri.indexOf("?" + key + "=") : i1;

        if (i == -1) {
            return uri;
        }

        int x = uri.indexOf('&', i + 1);

        String del;
        // 删除的是 第一个参数
        if (uri.charAt(i) == '?') {
            del = x != -1
                    // 如果有第二个参数
                    ? uri.substring(i + 1, x + 1)
                    // 如果无第二个参数
                    : uri.substring(i);
        } else {
            del = x != -1
                    // 不是最后一个参数
                    ? uri.substring(i, x)
                    // 是最后一个参数
                    : uri.substring(i);
        }

        return uri.replace(del, "");
    }

    public void setNextFilter(HttpRequestFilter nextFilter) {
        this.nextFilter = nextFilter;
    }
}
